import Cookies from 'js-cookie'

export class CookieStore extends DataStore {
  name = 'CookieStore'
  prefix = ''
  _keys = '__cookieds_keys__'
  expires = 365

  constructor(prefix = 'ds', expires = 365) {
    super()
    this.prefix = prefix
    this._keys = `${prefix}__cookieds_keys__`
    this.expires = expires
  }

  setItem(key, value) {
    Cookies.set(key, JSON.stringify(value), {expires: this.expires})
    let keys = this.getKeys()
    if (keys.findIndex(k => k === key) >= 0) {
      return
    }
    localStorage.setItem(this._keys, JSON.stringify([...keys, key]))
  }

  getItem(key) {
    const v = Cookies.get(key)
    if (v === undefined) {
      return undefined
    }
    return JSON.parse(v)
  }

  getKeys() {
    const v = localStorage.getItem(this._keys)
    if (v === undefined || v === null) {
      return []
    }
    return JSON.parse(v)
  }

  removeItem(key) {
    Cookies.remove(key)
    let keys = this.getKeys()
    keys = keys.filter(k => k !== key)
    localStorage.setItem(this._keys, JSON.stringify(keys))
  }

  clear() {
    let keys = this.getKeys()
    keys.forEach(k => {
        Cookies.remove(k)
      }
    )
    localStorage.removeItem(this._keys)
  }
}
